/**
 * 菜单相关工具函数
 */

/**
 * 将字符串转换为 PascalCase
 * @param {string} str - 输入字符串
 * @returns {string} PascalCase 字符串
 */
const toPascalCase = (str) => {
  return str
    .split('-')
    .map((word) => word.charAt(0).toUpperCase() + word.slice(1).toLowerCase())
    .join('');
};

/**
 * 将字符串转换为 kebab-case
 * @param {string} str - 输入字符串
 * @returns {string} kebab-case 字符串
 */
const toKebabCase = (str) => {
  return str.replace(/([a-z])(?=[A-Z])/g, '$1-').toLowerCase();
};

/**
 * 将字符串转换为 snake_case
 * @param {string} str - 输入字符串
 * @returns {string} snake_case 字符串
 */
const toSnakeCase = (str) => {
  return str.includes('-')
    ? str.replace('-', '_').toLowerCase()
    : str.toLowerCase();
};

/**
 * 根据 controller 生成数据库表名
 * @param {Array} parts - controller 分割后的部分
 * @returns {string} 数据库表名
 */
const generatetable_name = (parts) => {
  const table_nameParts = parts.map(toSnakeCase);
  return table_nameParts.join('_');
};

/**
 * 根据 controller 生成多语言键名
 * @param {Array} parts - controller 分割后的部分
 * @returns {string} 多语言键名
 */
const generateLangKey = (parts) => {
  const table_nameParts = parts.map(toKebabCase);
  return 'api.' + table_nameParts.join('.') + '.title';
};

/**
 * 根据 controller 生成菜单相关的详细信息
 * @param {string} controller - 控制器字符串，如 "System/User"
 * @returns {Object} 包含路由名称、路径、组件、表名和语言键的对象
 */
export const generateMenuDetails = (controller) => {
  if (!controller || typeof controller !== 'string') {
    throw new Error('Controller must be a non-empty string');
  }

  // 处理 controller 字符串
  const parts = controller
    .split('/')
    .map((part) => part.trim().replace(/([a-z])(?=[A-Z])/g, '$1-'))
    .filter((part) => part.length > 0); // 过滤空字符串

  if (parts.length === 0) {
    throw new Error('Controller must contain valid parts');
  }

  try {
    return {
      table_name: generatetable_name(parts),
      langKey: generateLangKey(parts),
    };
  } catch (error) {
    console.error('Error generating menu details:', error);
    throw new Error(
      `Failed to generate menu details for controller: ${controller}`,
    );
  }
};

/**
 * 验证生成的菜单详情是否有效
 * @param {Object} details - 菜单详情对象
 * @returns {boolean} 是否有效
 */
export const validateMenuDetails = (details) => {
  const requiredFields = ['table_name', 'langKey'];
  return requiredFields.every(
    (field) =>
      details[field] &&
      typeof details[field] === 'string' &&
      details[field].length > 0,
  );
};
